package com.xaicode.learn.netty.simple;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Locker xaicode@sina.com
 * @version 1.0
 * @date 2021/6/13 0013 23:47
 */
@Slf4j
public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    // on connect active
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        log.info("client ctx: {}", ctx);
        // send msg
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello, i am (σﾟ∀ﾟ)σ..:*☆哎哟不错哦", CharsetUtil.UTF_8));
    }

    // read
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        log.info("ctx: {}", ctx);

        // msg to netty byte buffer
        ByteBuf byteBuf = (ByteBuf) msg;
        log.info("read server [{}] msg: {}", ctx.channel().remoteAddress(), byteBuf.toString(CharsetUtil.UTF_8));
    }

    // on exception
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
